package com.mygame.gateway.server.handler.codec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xinyue.network.message.stream.EnumMesasageType;
import com.xinyue.network.message.stream.GatewayMessageHeader;
import com.xinyue.network.message.stream.TransferMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 解码客户端消息。协议格式为：格式见{@link GatewayMessageHeader}
 * 
 * @author wgs
 *
 */
public class DecodeHandler extends ChannelInboundHandlerAdapter {
	private Logger logger = LoggerFactory.getLogger(DecodeHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            ByteBuf byteBuf = (ByteBuf) msg;
            try {
                GatewayMessageHeader header = new GatewayMessageHeader();
                header.setMessageType(EnumMesasageType.REQUEST);
                header.read(byteBuf);
                ByteBuf bodyBuf = null;
                if (byteBuf.isReadable()) {
                   byte[] body = new byte[byteBuf.readableBytes()];
                   logger.debug("网关读取包体长度：{}",body.length);
                   byteBuf.readBytes(body);
                    // 判断消息是否加密了
                    if (header.isEncrypt()) {
                        // 如果加密了，就解密
                        //TODO 
                    }
                    // 判断消息是否压缩了
                    if (header.isCompress()) {
                        //解压
                        //TODO 
                    }
                    //重新使用ByteBuf包装
                    bodyBuf = Unpooled.wrappedBuffer(body);
                }
                TransferMessage transferMessage = new TransferMessage(header, bodyBuf);
                ctx.fireChannelRead(transferMessage);
            } finally {
                ReferenceCountUtil.safeRelease(byteBuf);
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}
